/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.model.tree;

import java.lang.reflect.Field;

import org.zhiqim.kernel.util.Asserts;
import org.zhiqim.kernel.util.Classes;
import org.zhiqim.kernel.util.Validates;

/**
 * 指定[父节点编号字段]和[子节点编号父字段]的值相等判断器<br>
 * 比如 FmrMenu对象有menuCode和parentCode两个字段<br>
 * 比较的时parent.menuCode == child.parentCode<br>
 *
 * @version v1.0.0 @author zouzhigang 2017-8-14 新建与整理
 */
public class TreeFielder<E> implements Treer<E>
{
    private String pFieldName;
    private String sFieldName;
    
    public TreeFielder(String pFieldName, String sFieldName)
    {
        this.pFieldName = pFieldName;
        this.sFieldName = sFieldName;
    }
    
    @Override
    public boolean isChildNode(E parent, E child)
    {
        try
        {
            //注意，这里是[父节点的自身字段]和[子节点的父字段]比较是否相等
            Field pField = Classes.getFieldDeep(parent.getClass(), sFieldName);
            Field sField = Classes.getFieldDeep(child.getClass(), pFieldName);
            
            pField.setAccessible(true);
            sField.setAccessible(true);
            
            Object pValue = pField.get(parent);
            Object sValue = sField.get(child);
            
            Asserts.as(pValue != null && sValue != null?null:"[树型菜单]编号和父编号字段值不允许为null");
            return Validates.isEqual(pValue, sValue);
        }
        catch (Exception e)
        {
            throw Asserts.exception("[树型菜单]"+e.getMessage());
        }
    }
}
